package ltd.dujiabao.mavenLocalInstaller.jar;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

import ltd.dujiabao.mavenLocalInstaller.domain.PomProperties;
import ltd.dujiabao.mavenLocalInstaller.util.MavenUtils;
import ltd.dujiabao.mavenLocalInstaller.util.PathUtils;

/**
 * @author : DuJiabao
 * @Project : mavenLocalInstaller
 * @Time : 2021/9/29 23:26
 * @Desc :
 */
public class JarInstaller {
    /**
     * @param filePath jar文件原始目录
     * @param tempDir  暂存目录，操作结束之后，会自动删除
     */
    public static void installAll(String filePath, String tempDir) {
        String localRepository = MavenUtils.getLocalRepositoryPath();
        List<String> paths = JarReader.saveSubJarFile(filePath, tempDir);
        for (String path : paths) {
            System.out.println("--------------------------- Begin to process " + path + " ---------------------------");
            PomProperties pomProperties = JarReader.getPomProperties(path);
            if (Objects.isNull(pomProperties)) {
                System.out.println(path + " contains no pom.properties");
            } else {
                String dirInRepository = localRepository + MavenUtils.getRelativeDirInRepository(pomProperties);
                //  先清空文件夹，再安装
                PathUtils.removeRf(dirInRepository);
                String result = MavenUtils.installJarLocally(path, pomProperties);
                System.out.println(result);
            }

            try {
                Files.delete(Paths.get(path));
                System.out.println("Success deleting " + path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("--------------------------- end\n\n \"---------------------------");
        }
    }
}
